// 查询记录

var identify = require("./identify.js");
var commonView = require("./commonView.js");
var $todayRecord, $selectType, $queryContent, $endDate, $startDate;
var selectTypeVal = "userId",
    maxPage;
var pageNo = 1,
    pageSize = 20;
var startDate = "",
    endDate = "";
// 取当天查询记录
function getTodayRecord() {
    var institution = $.cookie('institution');
    var name = $.cookie('name');
    var password = $.cookie('password');
    var paraments;
    $("#query-allpage").text("1");
    $("#query-nowpage").text("1");
    if (queryNavLi == "history") { // 条件查询
        var idCard, userName, pkgId;
        //        var startDate = ($("#startDate").datetimepicker("getDate")).setHours(0,0,0,1);
        // var endDate = ($("#endDate").datetimepicker("getDate")).setHours(23, 59, 59, 900);
        if (selectTypeVal == "userId") {
            idCard = $("#id-name_input").val();
        } else if (selectTypeVal == "name") {
            userName = $("#id-name_input").val();
        } else if (selectTypeVal == "groupName") {
            pkgId = $("#query-pkgid_select>option:checked").val();
        }
        paraments = {
            institution: institution,
            pageNo: pageNo,
            pageSize: pageSize,
            startDate: startDate,
            endDate: endDate,
            //            operatorPhone: operatorPhone,
            name: userName,
            pkgId: pkgId,
            idCard: idCard //身份证号
        };
    } else { // 查询当天
        var startDate2 = new Date((new Date()).setHours(0)).setMinutes(0);
        var endDate2 = new Date((new Date()).setHours(23)).setMinutes(23);
        paraments = {
            institution: institution,
            pageNo: pageNo,
            pageSize: pageSize,
            startDate: startDate2,
            endDate: endDate2
        };
    }


    $.post(queryRecordServlet, paraments, todayRecordBack);

}

// 当天记录回调函数
function todayRecordBack(tRecordData) {
    // console.dir(tRecordData);

    commonView.needLoading(tRecordData);
    var trHtml = '';
    if (tRecordData.totalCount && tRecordData.totalCount != 0) {
        $("#query-nowpage").text(pageNo);
        $("#query-allpage").text(tRecordData.totalPage);
        maxPage = tRecordData.totalPage;
        var totalCount = parseInt(tRecordData.totalCount);
        var RData = tRecordData.data;
        var groupMap = {
            "001": "组合A",
            "002": "组合B",
            "003": "组合C"
        };

        for (var i = 0, l = RData.length; i < l; i++) {
            var labelClass = "success";
            var statemsg = "查询成功";
            if (RData[i].queryStatus != "1") {
                labelClass = "important";
                statemsg = "查询失败";
            }

            var theId = i + 1 + ((pageNo - 1) * pageSize);
            var theDate = new Date(RData[i].insertime);
            var theDateformate = commonView.getDateFormate("yyyy-mm-dd hh:ii:ss", theDate);
            var groupName = groupMap[RData[i].pkgId];
            var thePone = "";
            if (RData[i].phone && RData[i].phone != "null" && RData[i].phone != "undefined") {
                thePone = RData[i].phone;
            }
            trHtml += `<tr><td>${theId}</td><td>${theDateformate}</td><td>${groupName}</td><td>${RData[i].name}</td><td><span class="label label-${labelClass}">${statemsg}</span></td><td><div class=""><a data-id="${RData[i].id}" data-name="${RData[i].name}" data-phone="${thePone}" data-time="${theDateformate}" data-pkid="${RData[i].pkgId}" class="btn label-primary btn-mini" href="javascript:;">查看</a></div></td></tr>`;
        }
        $("#today-record").find("tbody").html(trHtml);
        $("#today-record").find("a.btn").on("click", showDetails);
    } else {
        maxPage = 0;
        $("#today-record").find("tbody").html("<tr><td><p>没有查询记录</p></td></tr>");
    }

}

// 显示查询详情
function showDetails() {
    var $queryResult = $("#query-result");
    var $thisTarget = $(this);
    var theid = $thisTarget.data("id");
    var theName = $(this).data("name");
    var thePhone = $(this).data("phone");
    var selectTime = $(this).data("time");
    var thepkId = $(this).data("pkid");
    if (thepkId) {
        identify.setPkId(thepkId);
    }
    $.post(logDetailServlet, {
        id: theid
    }, function(detailData) {
        //  console.dir(detailData);
        commonView.needLoading(detailData);
        identify.resetIndentify();
//        $queryResult.empty();
        if (detailData.length) {
            for (var i = detailData.length - 1, l = 0; i >= l; i--) {
                identify.processingData(detailData[i], $queryResult, selectTime);
                /*                if(i == detailData.length - 1){
                                    if($("#basic-tb_0")[0]){
                                        $("#basic-tb_0").text(theName);
                                    }
                                    if($("#basic-tb_4")[0]){
                                        $("#basic-tb_4").text(thePhone);
                                    }
                                }*/
            }
        } else {
//            $queryResult.html('<p style="color: #f00;font-size: 20px;margin-top: 100px;text-align: center;">查询失败!</p>');
        }
    });
    if (queryNavLi == "history") {
        commonView.setQuery2Index(1);
    } else {
        commonView.setQuery2Index(0);
    }
    commonView.showStep("query2");
}

// 初始化查询界面
function initQueryRecord() {

    $startDate = $("#startDate").datetimepicker({
        //language:  'fr',
        weekStart: 1,
        todayBtn: 1,
        autoclose: 1,
        todayHighlight: 1,
        startView: 2,
        forceParse: 0,
        minView: 2,
        showMeridian: 1,
        language: "cn"
    });
    var newDate = new Date();
    newDate.setDate(newDate.getDate() + 1);
    $endDate = $("#endDate").datetimepicker({
        //language:  'fr',
        weekStart: 1,
        todayBtn: 1,
        autoclose: 1,
        todayHighlight: 1,
        startView: 2,
        forceParse: 0,
        minView: 2,
        showMeridian: 1,
        language: "cn",
        initialDate: newDate
    });
    $endDate.on("changeDate", function(ev) {
        //  console.log(ev.date.valueOf());
        if (ev.date) {
            endDate = ($("#endDate").datetimepicker("getDate")).setHours(23, 59, 59, 900);
        } else {
            endDate = "";
        }
    });
    $startDate.on("changeDate", function(ev) {
        //  console.log(ev.date.valueOf());
        if (ev.date) {
            startDate = ($("#startDate").datetimepicker("getDate")).setHours(0, 0, 0, 1); //ev.date.valueOf();
        } else {
            startDate = "";
        }

    });

    $selectType.on("change", function() {
        selectTypeVal = $selectType.find("option:checked").val();
        if (selectTypeVal == "groupName") {

            $("#query-content .col-my-4 input.form-input").hide();
            $("#query-content .col-my-4 select.form-input").show();
        } else {

            $("#query-content .col-my-4 input.form-input").show();
            $("#query-content .col-my-4 select.form-input").hide();
        }
    });

    bindEventAgain();
}

// 需要每次切换到查询时再次绑定的事件
function bindEventAgain() {
    $("a[data-value=intraday]").on("click", function() {
        commonView.showStep("query0");
        $queryContent.find(".query-parament").hide();
        $queryContent.find(".box-header>.title").text("当天查询记录");
        window.queryNavLi = "intraday";
        startDate = new Date((new Date()).setHours(0)).setMinutes(0);
        endDate = new Date((new Date()).setHours(23)).setMinutes(23);
        pageNo = 1;
        getTodayRecord();

    });
    $("a[data-value=history]").on("click", function() {
        commonView.showStep("query1");
        $queryContent.find(".query-parament").show();
        $queryContent.find(".box-header>.title").text("条件查询记录");
        window.queryNavLi = "history";
    });

}

// 初始化变量
(function initRecordValue() {
    $todayRecord = $("#today-record");
    $selectType = $("#select-type");
    $queryContent = $("#query-content");
    $("#query-record").on("click", function() {
        pageNo = 1;
        getTodayRecord();
    });
    $("#query-frist_page").on("click", function() {
        if (1 != pageNo) {
            pageNo = 1;
            getTodayRecord();
        }
    });
    $("#query-up_page").on("click", function() {
        if (pageNo > 1) {
            pageNo--;
            getTodayRecord();
        }
    });
    $("#query-next_page").on("click", function() {
        if (maxPage > pageNo) {
            pageNo++;
            getTodayRecord();
        }
    });
    $("#query-last_page").on("click", function() {
        if (maxPage != pageNo) {
            pageNo = maxPage;
            getTodayRecord();
        }
    });
    $("#today-record_refresh").on("click", function() {
        pageNo = 1;
        getTodayRecord();
    });
})();

module.exports = {
    getTodayRecord: getTodayRecord,
    initQueryRecord: initQueryRecord,
    bindEventAgain: bindEventAgain
};